package com.sdjzu.wanfuying.androiddesign.mvvm.coolapk;

import android.os.Bundle;
import android.view.ViewGroup;

import com.sdjzu.wanfuying.androiddesign.R;
import com.sdjzu.wanfuying.androiddesign.base.BaseActivity;
import com.sdjzu.wanfuying.androiddesign.databinding.CoolapkDataBinding;
import com.sdjzu.wanfuying.androiddesign.mvvm.coolapk.type.IViewHolder;
import com.sdjzu.wanfuying.androiddesign.mvvm.coolapk.type.TypeViewHolderFactory;

import java.util.Date;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;

public class CoolapkActivity extends BaseActivity {
    @BindView(R.id.activity_coolapk_recycler_view)
    RecyclerView recyclerView;
    private CoolapkViewModel coolapkViewModel;
    private ItemAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentViewWithDataBinding(R.layout.activity_coolapk);

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(adapter = new ItemAdapter());

        coolapkViewModel = new CoolapkViewModel();
        getViewDataBinding(CoolapkDataBinding.class).setVm(coolapkViewModel);

        loopOnUiThread(() -> {
            for (Item item : coolapkViewModel.getItemList()) {
                item.setContent(new Date((long) (Math.random() * System.currentTimeMillis())).toLocaleString());
            }
        }, 1000L, 1000L);
    }

    class ItemAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        @Override
        public int getItemViewType(int position) {
            return coolapkViewModel.getItemList().get(position).getType();
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return TypeViewHolderFactory.inflate(getLayoutInflater(), parent, viewType);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            if (holder instanceof IViewHolder) {
                ((IViewHolder) holder).setItem(coolapkViewModel.getItemList().get(position));
            }
        }

        @Override
        public int getItemCount() {
            return coolapkViewModel.getItemList().size();
        }

    }
}
